//
//  PAGroupManager.m
//  PilotSeries
//
//  Created by 黄立强 on 16/6/30.
//  Copyright © 2016年 leon.huang. All rights reserved.
//

#import "PAGroupManager.h"
#import "FMDB.h"
#import "ChartGroup.h"
#import "ChartConfig.h"
@implementation PAGroupManager
static FMDatabase *_db;

+ (void)initialize
{
    // 1.获得数据库文件的路径
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filename = [doc stringByAppendingPathComponent:@"pilot.sqlite"];
    
    // 2.得到数据库
    _db = [FMDatabase databaseWithPath:filename];
    
    // 3.打开数据库
    if ([_db open]) {
//        [_db executeUpdate:@"DROP TABLE IF NOT EXISTS t_chart_group;"];

        // 4.创表
        BOOL result = [_db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_chart_group (id integer PRIMARY KEY AUTOINCREMENT, username text NOT NULL,env integer NOT NULL,chart_configs blob,group_name text NOT NULL);"];
        if (result) {
            LOG(@"成功创表")
        } else {
            LOG(@"创表失败")
        }
        
    }
}

/**
 *  获取所有的groupName
 *
 *  @return
 */
+(NSArray *)loadGroupName{
    
    NSString *username = [PAAppContext sharedInstance].username;
    NSInteger env = [PAAppContext sharedInstance].envType;
    NSMutableArray *groupNames = [NSMutableArray new];
    FMResultSet *resultSet = nil;
    resultSet = [_db executeQuery:@"SELECT DISTINCT group_name FROM t_chart_group WHERE username = ? AND env = ? ;",username,@(env)];
    // 遍历查询结果
    while (resultSet.next) {
        NSString *groupName = [resultSet stringForColumn:@"group_name"];
        [groupNames addObject:groupName];
        
    }
    
    return groupNames;
}

/**
 *  根据groupName 获取所有的ChartGroup
 *
 *  @param groupName
 *
 *  @return 
 */
+(ChartGroup *)loadGroupByGroupName:(NSString *)groupName{
    NSString *username = [PAAppContext sharedInstance].username;
    NSInteger env = [PAAppContext sharedInstance].envType;
    ChartGroup *chartGroup;
    FMResultSet *resultSet = nil;
    resultSet = [_db executeQuery:@"SELECT * FROM t_chart_group WHERE username = ? AND env = ? AND group_name = ?;",username,@(env),groupName];
    // 遍历查询结果
    while (resultSet.next) {
        chartGroup = [ChartGroup new];
        
        NSData *config = [resultSet objectForColumnName:@"chart_configs"];
        NSString *groupName = [resultSet stringForColumn:@"group_name"];
        NSArray  *chartConfigs = [NSKeyedUnarchiver unarchiveObjectWithData:config];
        chartGroup.groupName = groupName;
        chartGroup.chartConfigs = chartConfigs;
    }
    return chartGroup;
}

/**
 *  添加或者修改group
 *
 *  @param groupName
 *  @param chartNames
 */
+(void) updateGroup:(NSString *)groupName withChartNames:(NSArray *)chartNames{
    
    NSString *username = [PAAppContext sharedInstance].username;
    NSInteger env = [PAAppContext sharedInstance].envType;
    ChartGroup *chartGroup = [self loadGroupByGroupName:groupName];
    NSData *data =[NSKeyedArchiver archivedDataWithRootObject:chartNames];
    
    BOOL result;
    if (chartGroup!=nil) {
        
        result = [_db executeUpdate:@"UPDATE t_chart_group set chart_configs = ? where username = ? AND env = ? AND group_name = ?",data,username,@(env),groupName];
        
    }else{
      result =  [_db executeUpdate:@"INSERT INTO t_chart_group (username, group_name, chart_configs,env) VALUES (?, ?, ?,?);",username,groupName,data,@(env)];
        
    }
    if (result) {
        LOG(@"updateGroup %@ withChartConfigs %@ success!",groupName,chartNames)
    }else{
        DDLogError(@"updateGroup %@  withChartConfigs %@ fail!",groupName,chartNames);
    }
    
}

+(void) deleteGroup:(NSString *)groupName{
    NSString *username = [PAAppContext sharedInstance].username;
    NSInteger env = [PAAppContext sharedInstance].envType;
    BOOL result = [_db executeUpdate:@"DELETE FROM t_chart_group where username = ? AND env = ? AND group_name = ?",username,@(env),groupName];
    if (result) {
        LOG(@"deleteGroup %@ success!",groupName)
    }else{
        DDLogError(@"deleteGroup %@ fail!",groupName);
    }
}

/**
 *  确保group已经存在,添加chartConfig到群组中，如果群组中已经有了，则更新，没有则添加
 *
 *  @param chartConfig not nil
 *  @param groupName   not nil
 */
+(NSInteger)addChartConfig:(NSString *)chartName toGroup:(NSString *)groupName{
    NSString *username = [PAAppContext sharedInstance].username;
    NSInteger env = [PAAppContext sharedInstance].envType;
    ChartGroup *chartGroup = [self loadGroupByGroupName:groupName];
    NSMutableArray *chartConfigs = [chartGroup.chartConfigs mutableCopy];
    NSInteger index = [chartConfigs indexOfObject:chartName];
    if (index ==NSNotFound) {
        [chartConfigs addObject:chartName];
    }else{
        [chartConfigs replaceObjectAtIndex:index withObject:chartName];
    }
    NSData *data =[NSKeyedArchiver archivedDataWithRootObject:chartConfigs];
    
    [_db executeUpdate:@"UPDATE t_chart_group set chart_configs = ? where username = ? AND env = ? AND group_name = ?",data,username,@(env),groupName];
    return index;
    
}

//+(void)deleteChartConfig:(NSString *)chartName fromGroup:(NSString *)groupName{
//    
//    
//    
//}
@end
